package com.example.bootcurriculumproject.filter;

import com.example.bootcurriculumproject.util.RedisUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.io.PrintWriter;

//@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("进入过滤器");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求的URL
        String requestURL=request.getRequestURI();
        //定义无需处理的URL
        String[] urls = new String[]{
          "/user/login",
          "/user/register",
          "/user/loginOut",
                "/goods/geiAll"
                ,"/user/getUserByUid"
        };
        //判断本次请求是否需要处理
        boolean check = check(urls,requestURL);
        if(check){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        if(redisUtil.hasKey("nowUid")){
            log.info("用户登录了于是放行");
            //用户已经登录了--》放行
            filterChain.doFilter(request,response);
        }else {
            log.info("用户没有登录，需要登录后在访问功能，发送此时状态码-->message:NOTLOGIN");
            PrintWriter writer = response.getWriter();
            response.setCharacterEncoding("UTf-8");
            response.setContentType("application/json; charset=utf-8");
            writer.write("{\"messqge\":\"NOTLOGIN\"}");
            writer.flush();
            writer.close();
        }
    }
    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
